package com.origon.managedbeans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Principal;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.event.FileUploadEvent;

import com.origon.entities.Deal;
import com.origon.entities.Product;
import com.origon.entities.Shop;
import com.origon.entities.User;
import com.origon360.Services.ProductService;
import com.origon360.utilities.NavigationHelper;
import com.origon360.utilities.SessionUtil;

@ManagedBean(name="productBean")
@SessionScoped
public class ProductBean{
	
	private static Log logger = LogFactory.getLog(ProductBean.class);
	
	@EJB
	private ProductService productService;
	
	//private String filedestination = SessionUtil.getExternalContext().getRealPath("/resources/images/products/");
	
		
	private String filedestination = "D:\\Nissi-Dev\\eclipse\\workbench\\Origon360\\src\\main\\webapp\\resources\\images\\products\\";
	
	
	private Product product = new Product();
	
	private Product selectedProduct;
	
	private String productImage;
	
	private Shop shop;
	
	private User user;
	
	private List<Product> productListPerShop;
	
	private List<Shop> userShopList;
	
	private List<Deal> dealList;
	
	
	
	public String initShopDetail(ComponentSystemEvent event){
		
		boolean isPostback = SessionUtil.getFacesContext().isPostback() ;
		
		if(!isPostback)
		{
			
			this.shop = SessionUtil.getSelectedShop();
			if(shop == null)
			{
				logger.info("shop is null...!");
				
				return NavigationHelper.SHOW_SHOPS_URI;
			}
			
		}
		return null;
	}
	
	
	public String initProductDetails(ComponentSystemEvent event){
		boolean istPostback = SessionUtil.getFacesContext().isPostback();
		
		if(!istPostback)
		{
			this.selectedProduct = SessionUtil.getSelectedProduct();
			if(shop == null)
			{
				return NavigationHelper.SHOW_SHOP_URI;
			}
		}
		return null;
	}
	
	public void initUserShopList()
	{
		User user = SessionUtil.getSessionUser();
		userShopList = productService.fetchShopsPerUser(user.getId());
	}
	
	


	public Product getProduct() {
		return product;
	}
 
	public void setProduct(Product product) {
			
		this.product = product;
	}

	public Product getSelectedProduct() {
		return selectedProduct;
	}


	public void setSelectedProduct(Product selectedProduct) {
		this.selectedProduct = selectedProduct;
	}


	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}	
	
	public List<Product> getProductListPerShop() {
		
			String shopId = shop.getId();
			productListPerShop = productService.fetchProductsPerShop(shopId);
		
		return productListPerShop;
	}

	public void setProductListPerShop(List<Product> productListPerShop) {
		this.productListPerShop = productListPerShop;
	}

	public List<Shop> getUserShopList() {
		if(userShopList == null)
		{
			initUserShopList();
		}
		return userShopList;
	}

	public void setUserShopList(List<Shop> userShopList) {
		this.userShopList = userShopList;
	}


	public List<Deal> getDealList() {
		if(dealList == null)
		{
			dealList = productService.fetchDeals();
		}
		return dealList;
	}

	public void setDealList(List<Deal> dealList) {
		this.dealList = dealList;
	}

	public String navigateToCreateProduct(){
			String url =  NavigationHelper.CREATE_PRODUCT_URI;
		return url;
		
	}
	
	public String navigateToProduct(Product product){
		if(SessionUtil.getSessionUser() == null)
		{
			return NavigationHelper.HOME_URI;
		}
			else
		{
			return NavigationHelper.PRODUCT_URI;
		}
	
	}
	
	public void addMessage(String msg){
		FacesMessage facesMessage = new FacesMessage(msg);
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);
	}
	
	public void createProduct(){
		try {
			
			product.setImageName(productImage);
			product.setShop(shop);
			productService.createProduct(product);
			String message = "Product was successfully Created";
			addMessage(message);
			
			logger.info(filedestination);
			
		} catch (Exception e) {
			String message = "Product creation failed";
			addMessage(message);
			
		}
	}
	
	
	public void uploadProductImage(FileUploadEvent event){
		
		try {
			productImage = event.getFile().getFileName();
			copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
				addMessage(event.getFile().getFileName()+"was successfully uploaded");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void copyFile(String fileName, InputStream in){
		try {
			OutputStream out = new FileOutputStream(new File(filedestination+fileName));
			int read = 0;
			byte[] bytes = new byte[1024];
			
			while( (read = in.read(bytes)) != -1 )
			{
				out.write(bytes, 0, read);
			}
			in.close();
			out.flush();
			out.close();
			logger.info("Product image successfuly uploaded...!");
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		
	}
	
	

}
